package com.ticket.sass.admin.manager;

import com.ticket.sass.admin.handler.IdentityInput;

/**
 * 用于全局缓存身份信息
 * @author ywb
 * @date 2024-05-27 15:21
 */
public class ThreadLocalIdInputHolderManager {
    
    private static final ThreadLocal<IdentityInput> valueHolder = new ThreadLocal<>();
    
    public static void setValue(IdentityInput value) {
        valueHolder.set(value);
    }
    
    public static IdentityInput getValue() {
        return valueHolder.get();
    }
    
    public static IdentityInput getNotNullValue() {
        IdentityInput value = valueHolder.get();
        if (value == null) {
            throw new IllegalStateException("在ThreadLocal中找不到IdentityInput");
        }
        return value;
    }
    
    public static void remove() {
        valueHolder.remove();
    }
    
    public static <T> T autoInjectDestroy(IdentityInput identity, Callback<T> callback) {
        try {
            setValue(identity);
            return callback.call();
        } finally {
            remove();
        }
    }
    
    public interface Callback<T> {
        T call();
    }
    
    
}

